import { isLeapYear, createArrayFrom } from 'bee/utils';

function createDateData(start = '1970-1-1', end = '2020-1-1') {
  let date = [];
  // 起止时间范围，格式为xxxx-yy-dd

  const [startY, startM, startD] = start.split('-').map(v => parseInt(v, 10));
  const [endY, endM, endD] = end.split('-').map(v => parseInt(v, 10));

  // 根据起止年份显示年份选择
  const years = createArrayFrom({ length: endY - startY + 1, start: startY });

  date = years.map(year => {
    // 根据起止月份显示月份选择
    const startMonth = year === startY ? startM : 1;
    const endMonth = year === endY ? endM : 12;
    const months = createArrayFrom({
      length: endMonth + 1 - startM,
      start: startMonth,
    });

    const temp = months.map(month => {
      const startDay = year === startY && month === startM ? startD : 1;

      let lastDay = 30;

      // 渲染截至日期，最后一天为endD
      if (year === endY && month === endM) {
        lastDay = endD;
      }

      if (month === 2) {
        // 闰年2月为29号
        if (isLeapYear(year)) {
          lastDay = 29;
        } else {
          // 非闰年2月最后一天为28号
          lastDay = 28;
        }
      }

      // 1、3、5、7、8、10、12月 ，最后一天为31号
      if ([1, 3, 5, 7, 8, 10, 12].indexOf(month) > -1) {
        lastDay = 31;
      }

      return {
        [month]: createArrayFrom({
          length: lastDay + 1 - startDay,
          start: startDay,
        }),
      };
    });

    return { [year]: temp };
  });

  return date;
}

export { createDateData };
